﻿namespace MicroCloud.Extensions
{
    #region "<see cref="IConfiguration"/> 扩展方法"
    /// <summary>
    /// <see cref="IConfiguration"/> 扩展方法
    /// </summary>
    public static class ConfigurationExtensions
    {
        #region "扩展方法"
        #region "从 <see cref="IConfiguration"/> 获取 <see cref="MicroCloudOptions"/>"
        /// <summary>
        /// 从 <see cref="IConfiguration"/> 获取 <see cref="MicroCloudOptions"/>
        /// </summary>
        /// <param name="configuration"></param>
        /// <returns>系统配置选项信息</returns>
        public static MicroCloudOptions GetMicroCloudOptions(this IConfiguration configuration)
        {
            var options = Singleton<MicroCloudOptions>.Instance;
            if (options == null)
            {
                if (configuration != null)
                {
                    options = new();
                    new MicroCloudOptionsSetup(configuration).Configure(options);
                }
            }
            return options;
        }
        #endregion
        #region "从 <see cref="IConfiguration"/> 获取指定类型的配置选项"
        /// <summary>
        /// 从 <see cref="IConfiguration"/> 获取指定类型的配置选项
        /// </summary>
        /// <typeparam name="TOptions">配置选项类型</typeparam>
        /// <param name="configuration"></param>
        /// <param name="key">节点名称，多节点以:分隔</param>
        /// <param name="setupFunc">自定义设置配置选项委托方法</param>
        /// <returns>指定类型的配置选项</returns>
        public static TOptions GetOptions<TOptions>(this IConfiguration configuration, string key, Func<IConfiguration, string, TOptions> setupFunc = null)
            where TOptions : class, new()
        {
            var options = Singleton<TOptions>.Instance;
            if (options == null && configuration != null && setupFunc != null)
            {
                options = new();
            }
            if (configuration != null)
            {
                if (setupFunc != null)
                {
                    options = setupFunc(configuration, key);
                }
                else
                {
                    Check.NotNullOrEmpty(key, nameof(key));
                    var section = configuration.GetSection(key);
                    options = section.Get<TOptions>();
                }

                if (options != null)
                {
                    Singleton<TOptions>.Instance = options;
                }
            }
            return options;
        }
        #endregion

        #endregion

    }
    #endregion

}
